package org.glorylight.hacks.social.controller;

import java.util.Date;

import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.apache.commons.lang3.RandomStringUtils;
import org.glorylight.hacks.social.data.MailMe;
import org.glorylight.hacks.social.data.UserData;
import org.glorylight.hacks.social.service.MailService;
import org.glorylight.hacks.social.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

@Component
@Scope("prototype")
@Path("/registration")
public class RegistrationController extends AbstractBaseController {
	
	private static final Logger log = LoggerFactory.getLogger(RegistrationController.class);
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private MailService mailService;

	@POST
	@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
	public Response registrationStep1(@FormParam("mail") String email, @FormParam("firstName") String firstName, @FormParam("lastName") String lastName, @FormParam("invitationId") String invitationId) {
		String generatedPassword = RandomStringUtils.random(10, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890~!@#$%^&*()<>{}-+=?");
		UserData userData = new UserData(email, generatedPassword, firstName, lastName, new Date(), false);
		try {
			userService.addUser(userData);
			MailMe mail = new MailMe("Activate your Babytivities account", 
					"noreply@babytivities.com", 
					new String[] {email}, 
					"confirmation", 
					new String[]{firstName + " " + lastName, "http://www.babytivities.com/activation.php?q="+userService.find(email).getUserId(), email, generatedPassword});
			mailService.sendMail(mail);
		} catch(Exception e) {
			log.error("could not register user", e);
			return Response.status(Response.Status.CONFLICT).build();
		}
		return Response.status(Response.Status.CREATED).build();
	}
}
